package com.lianzhihui.romeex.ui.me.download;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;


import com.lianzhihui.romeex.R;
import com.lianzhihui.romeex.config.AppConstants;
import com.lianzhihui.romeex.config.MessageEvent;
import com.lianzhihui.romeex.utils.LogUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * @author 下载
 */
public class ApkDownLoadService extends IntentService {

    private long downId;

    private DownloadInfo dlInfo;

    private DownloadManager dwManager;

    private NotificationCompat.Builder builder;

    private NotificationManager notificationManager;

    private Notification notification;

    public static final String sID = "channel_1";
    public static final String sName = "Primary Channel";

    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();

    //是否完成
    private boolean isCompleted;

    public ApkDownLoadService() {
        super("ApkDownLoadService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (dlInfo == null || dwManager == null) {
            this.dlInfo = (DownloadInfo) intent.getSerializableExtra("taskInfo");
            downloadApk(dlInfo);
            initNotification();
            return;
        }

        dispose();


    }

    /**
     * 通知
     */
    @SuppressLint("StringFormatMatches")
    private void initNotification() {
        notificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(sID, sName, NotificationManager.IMPORTANCE_LOW);
            channel.setLightColor(Color.RED);
            //channel.enableLights(true);
            //channel.enableVibration(true);
            //channel.setSound(null, null);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            notificationManager.createNotificationChannel(channel);

            builder = new NotificationCompat.Builder(this, sID);
        } else {
            builder = new NotificationCompat.Builder(this, null);
        }
        builder.setContentTitle(getString(R.string.update_prepare, new Object[]{getString(R.string.app_name)}))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setDefaults(Notification.DEFAULT_LIGHTS)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(false)
                .setContentText(String.format(getString(R.string.update_prepare), new Object[]{Integer.valueOf(1), "%"}))
                .setProgress(100, 0, false);
        builder.setOnlyAlertOnce(true);
        notification = this.builder.build();
    }

    /**
     * @param dlInfo
     */
    private void downloadApk(DownloadInfo dlInfo) {
        dwManager = (DownloadManager) getSystemService(Service.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(dlInfo.getDownloadUrl());
        //下载请求
        DownloadManager.Request request = new DownloadManager.Request(uri);
        //
        request.setTitle(getString(R.string.update_prepare, new Object[]{getString(R.string.app_name)}));
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        request.setAllowedOverRoaming(false);
        request.setMimeType("application/vnd.android.package-archive");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION);
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdir();
        File file = new File(dlInfo.getApkLocalPath());
        if (file.exists()) {
            file.delete();
        }
        request.setDestinationUri(Uri.fromFile(file));
        downId = this.dwManager.enqueue(request);

        sendApkUpdate();
    }

    /**
     * 下载更新
     */
    public void sendApkUpdate() {
        Observable.interval(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .takeUntil(aLong -> {
                    return isCompleted;
                })
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mCompositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(Long aLong) {
                        checkDownloadStatus();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtil.error("ApkDownLoadService===>", "==e====" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        LogUtil.error("ApkDownLoadService===>", "==onComplete====");
                        dispose();
                    }
                });
    }

    /**
     * 更新下载状态
     */
    private void checkDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        //筛选下载任务
        query.setFilterById(downId);
        Cursor cursor = dwManager.query(query);
        if (cursor.moveToFirst()) {
            //已下载
            long downloadedBytes =
                    cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
            //文件大小
            long totalBytes = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
            // 下载状态
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                //下载暂停， 由系统触发
                case DownloadManager.STATUS_PAUSED:

                    break;
                //下载延迟， 由系统触发
                case DownloadManager.STATUS_PENDING:

                    break;
                case DownloadManager.STATUS_RUNNING:
                    int progress = (int) ((downloadedBytes * 100) / totalBytes);
                    builder.setProgress(100, progress, false);
                    builder.setContentText(String.format(getString(R.string.update_progress), new Object[]{progress, "%"}));
                    String jsonObj = totalBytes + "," + downloadedBytes;
                    LogUtil.error("xxxx",jsonObj);
                    EventBus.getDefault().post(new MessageEvent(AppConstants.Event.UPDATE_VERSION, jsonObj));
                    notificationManager.notify(1, builder.build());
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    builder.setContentText(getResources().getString(R.string.update_finish));
                    notificationManager.cancel(1);
                    isCompleted = true;
                    dispose();
                    openFile();
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 打开文件安装
     */
    public void openFile() {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        File file = new File(dlInfo.getApkLocalPath());

        LogUtil.error("ApkDownLoadService===>", "file====" + file.getAbsolutePath());
        Uri data = FileProvider.getUriForFile(getApplication(), "com.lianzhihui.romeex.fileprovider", file);
        // 给目标应用一个临时授权
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        intent.setDataAndType(data,
                "application/vnd.android.package-archive");
        startActivity(intent);
    }


    private void dispose() {
        if (mCompositeDisposable != null && !mCompositeDisposable.isDisposed()) {
            mCompositeDisposable.dispose();
        }
    }

}
